package com.sakiko.otherai.controller;

import com.alibaba.cloud.ai.dashscope.image.DashScopeImageModel;
import com.alibaba.cloud.ai.dashscope.image.DashScopeImageOptions;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.ai.image.ImagePrompt;
import org.springframework.ai.image.ImageResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URL;

/**
 * projectName: com.sakiko.otherai.controller
 *
 * @author: Yang
 * description: 图像生成模型体验
 * time: 2025/8/8 22:39
 */
@RestController
public class ImageModelController {

    @Autowired
    private DashScopeImageModel imageModel;

    @GetMapping("/image")
    public void getImage(@RequestParam(value = "msg", defaultValue = "生成一只小猪") String msg, HttpServletResponse response) {
        ImageResponse imageResponse = imageModel.call(
                new ImagePrompt(
                        msg,
                        DashScopeImageOptions.builder()
                                .withModel("wan2.2-t2i-flash")
                                .withN(1) // 生成图像数量
                                .withHeight(512) // 设置图像高度
                                .withWidth(512) // 设置图像宽度
                                .build()
                )
        );
        // 生成图像地址
        String imageUrl = imageResponse.getResult().getOutput().getUrl();
        // 在浏览器上输出
        try {
            URL url = URI.create(imageUrl).toURL();
            InputStream in = url.openStream();
            response.setHeader("Content-Type", MediaType.IMAGE_PNG_VALUE);
            response.getOutputStream().write(in.readAllBytes());
            response.getOutputStream().flush();
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }


}
